package com.bbx.taxi.client.Task;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.net.base.BaseNetwork;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Bean.Message.ObserverListener;
import com.bbx.taxi.client.Bean.Message.Publisher;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_TYPE;

public abstract class BaseTask {
   public  Context context;
   public  DATA_TYPE TYPE;
   /**发送请求*/
   public abstract void request();
   /**获取是否弹窗加载框*/
   public abstract boolean isShow();
   
   public abstract BaseNetwork getBaseNetwork();
   /**判断返回的类型，通常情况为false返回json，true返回String类型*/
   public abstract boolean isReturnString();
   
   /**加载成功*/
   public abstract void success(int status,Object object);
   /**加载失败,
    * message为返回的全部信息，
    * msg 为解析出message里的内容
    * */
   public abstract void failed(int status, String msg,String message);
   /**设置条件，主要用于区分是不是当前请求如果为false则不做任何处理。.如果不需要请默认为true*/
   public abstract boolean condition();
   public Publisher mPublisher;
   public BaseTask(Context context) {
	   this.context = context;
	   mPublisher=Publisher.getInstance();
     }
	boolean encrypt=true;
	public void setEncrypt(boolean encrypt){
		this.encrypt=encrypt;
	}
	public boolean getEncrypt(){
		return  encrypt;
	}
   public void setType(DATA_TYPE TYPE,Object object){
	   this.TYPE=TYPE;
	   new MyBaseTask(context,object).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
   }
	private class MyBaseTask extends BaseAsyncTask {
	
		public Object object;
		public MyBaseTask(Context context,Object object) {
			super(context,isShow());
			setIsReturnString(isReturnString());
			this.object=object;
		}

		@Override
		public void onSuccess(int status,Object object) {
			if(!condition())return;
			success(status,object);
			if (object != null) {
	            mPublisher.publishdata(ObserverListener.DATA_STATUS.SUCCESS, TYPE,status,object);
			} else {
	            mPublisher.publishdata(ObserverListener.DATA_STATUS.FAIL, TYPE,status,null);
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			if(!condition())return;
			JSONObject jmsg;
			try {
				jmsg = new JSONObject(msg);
				 failed(status, msg,jmsg.getString("message"));
			} catch (JSONException e) {
				 failed(status, msg,context.getResources().getString(R.string.no_network));
			}
           mPublisher.publishdata(ObserverListener.DATA_STATUS.FAIL, TYPE,status,null);
		}

		@Override
		protected Object doInBackground(Object... params) {
			String json="";
			if(getEncrypt()){
				json = new JsonBuild().setModel(object).getJson();
			}else{
				json = new JsonBuild().setModel(object).getJsonString();
			}

			BaseNetwork basenet=getBaseNetwork();
			basenet.setData(json);
			return basenet;
		}
	}

}
